package concurrent.tool;

import java.util.concurrent.Exchanger;

/**
 * 用于两个线程(只能两个线程)之间交换数据
 */
public class ExchangerTest {

    public static void main(String[] args) {

        Exchanger<String> exchanger = new Exchanger<>();

        new Thread() {
            @Override
            public void run() {
                try {
                    String exchange = exchanger.exchange("A");
                    System.out.println(getName() + ":" + exchange);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    String exchange = exchanger.exchange("B");
                    System.out.println(getName() + ":" + exchange);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
